const Router = require('koa-router');
const router = new Router();
const List = require('../models/list');
const Detail = require('../models/detail');
const { Op } = require('sequelize');
// list查询
router.get('/api/order-list', async (ctx) => {
    const { date, dealer, son } = ctx.query; // 从查询参数中获取日期、经销商和子项
    
    const whereClause = {};
    
    if (date) {
        const [year, month] = date.split('-');
        const startDate = `${year}-${month.padStart(2, '0')}-01`;
        const endDate = `${year}-${month.padStart(2, '0')}-31`;
        whereClause.ctime = {
            [Op.between]: [startDate, endDate]
        };
    }
    
    if (dealer) {
        whereClause.dealer = dealer;
    }
    
    if (son) {
        whereClause.son = son;
    }
    
    const users = await List.findAll({
        where: whereClause
    });
    
    if (users && users.length > 0) {
        ctx.body = users.map(user => user.toJSON());
    } else {
        ctx.status = 404;
    }
});


// 订单查询
router.get('/api/order/:oid', async (ctx) => {
    const oid = ctx.params.oid; // 从URL参数中获取id
    const user = await List.findOne({ where: { oid } }); // 根据id查询数据

    if (user) {
        ctx.body = user.toJSON(); // 将查询结果作为JSON返回
    } else {
        ctx.status = 404; // 如果未找到数据，返回404
    }
});



// 创建订单
router.post('/api/new-order', async (ctx, next) => {
    const orderData = ctx.request.body; // 直接获取整个请求体对象

    try {
        const item = await List.create(orderData); // 直接传入整个对象
        ctx.body = item;
    } catch (error) {
        console.error('创建订单失败：', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '创建失败',
            error: error.message,  // 添加错误详细信息
        };
    }
});

// 修改订单
router.put('/api/update-order/:oid', async (ctx) => {
    const oid = ctx.params.oid;
    const updateData = ctx.request.body;

    try {
        const [affectedCount] = await List.update(updateData, {
            where: { oid }
        });

        if (affectedCount > 0) {
            ctx.status = 200;
            ctx.body = { 
                success: true,
                message: '订单更新成功'
            };
        } else {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '未找到指定订单'
            };
        }
    } catch (error) {
        console.error('修改订单失败：', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '修改订单失败'
        };
    }
});

// 删除订单及详情
router.delete('/api/order/:oid', async (ctx) => {
    const oid = ctx.params.oid;
    try {
        // 删除订单
        const orderDeleted = await List.destroy({ where: { oid } });
        // 删除订单详情
        const detailDeleted = await Detail.destroy({ where: { oid } });
        
        if (orderDeleted > 0 || detailDeleted > 0) {
            ctx.status = 200;
            ctx.body = {
                success: true,
                message: '订单及详情删除成功',
                orderDeleted: orderDeleted > 0,
                detailDeleted: detailDeleted > 0
            };
        } else {
            ctx.status = 404;
            ctx.body = {
                success: false,
                message: '未找到指定订单或详情'
            };
        }
    } catch (error) {
        console.error('删除订单失败：', error);
        ctx.status = 500;
        ctx.body = {
            success: false,
            message: '删除订单失败',
            error: error.message
        };
    }
});
module.exports = app => {
    app.use(router.routes())
        .use(router.allowedMethods())
}
